package cc.momas.momall.search.service.impl;

import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cc.momas.common.vo.SearchResult;
import cc.momas.momall.search.dao.SearchDao;
import cc.momas.momall.search.service.SearchService;

@Service("searchServiceImpl")
public class SearchServiceImpl implements SearchService {

	@Autowired
	private SearchDao searchDao;

	@Override
	public SearchResult search(String keyword, int page, int rows) throws Exception {
		// 创建一个SolrQuery对象
		SolrQuery solrQuery = new SolrQuery();
		// 设置查询条件
		solrQuery.setQuery(keyword);
		// 设置分页条件
		if (page <= 0) {
			page = 1;
		}
		// 设置默认搜索域
		solrQuery.set("df", "product_name");
		// 开启高亮显示
		solrQuery.setHighlight(true);
		solrQuery.addHighlightField("product_name");
		// 设置高亮字符包围
		solrQuery.setHighlightSimplePre("<em style=\"color:red\">");
		solrQuery.setHighlightSimplePost("</em>");

		// 调用dao查询
		SearchResult search = searchDao.search(solrQuery);
		// 计算总页数
		long recordCount = search.getRecordCount();
		int totalPage = (int) (recordCount / rows);
		if (recordCount % rows > 0) {
			totalPage++;
		}
		// 添加到返回结果
		search.setTotalPages(totalPage);
		return search;
	}

}
